import java.util.Date

import com.rectcircle.config.DbConfig
import com.rectcircle.config.LibraryDbSchema._
import com.rectcircle.dao.{AuthorDao, BookDao, BorrowalDao, ReaderDao}
import com.rectcircle.model.{Author, Book, Borrowal, Reader}
import org.slf4j.LoggerFactory
import org.squeryl.SessionFactory

object Main extends App {
	val logger = LoggerFactory.getLogger(getClass)
	//http://www.scalatra.org/2.4/guides/persistence/squeryl.html
	//前端控制器使用scalatra或者Spray
	//业务逻辑Akka actor方式
	
	//初始化数据库配置，测试在这，未来交由框架初始化函数调用
	DbConfig.init
	//绑定session，未来交由前端过滤器调用
	val session = SessionFactory.newSession
	session.bindToCurrentThread
//	org.squeryl.Session.currentSession.setLogger(logger.debug)
	org.squeryl.Session.currentSession.setLogger(println)
	
	println("initializing the weKanban schema")
	
	//tx事务管理交由service控制
	tx{ drop; create; printDdl}
	
	tx{
		addTestData
	}

	val tomBooks = BookDao.getBooksByAuthorName("tom")
	tomBooks.foreach(b=>println(s"${b.title}"))
	
	val bookWithAuthor = BookDao.getBooksWithAuthorByName("tomBook1")
	
	bookWithAuthor.foreach(ba=>println(s"title:${ba._1.title} author:${ba._2.firstName}"))

	AuthorDao.getAllBookOfAuthors.foreach(println)
	
	//多对一、一对多关系映射
	val tom = AuthorDao.getByFirstName("tom")
	AuthorDao.withBooks(tom)
	println(tom.books)
	
	//测试多对多
	val reader1 = ReaderDao.getByUsername("R1")
	ReaderDao.withBooks(reader1)
	reader1.books.foreach(println)
	
	//解绑session，交由框架调用
	session.unbindFromCurrentThread
	
	def addTestData ={
		//作者测试数据
		val tom = AuthorDao.save(Author("Tom","",Some("tom@163.com")))
		val rectcircle =  AuthorDao.save(Author("Rectcircle","",Some("rectcircle@gmail.com")))
		val job =  AuthorDao.save(Author("Job","",Some("job73@gmail.com")))
		
		//书籍测试数据
		val tomBook1 = BookDao.save(Book("tomBook1",tom.id,None))
		val tomBook2 = BookDao.save(Book("tomBook2",tom.id,None))
		val tomBook3 = BookDao.save(Book("tomBook3",tom.id,None))
		
		val rectcircleBook1 = BookDao.save(Book("rectcircleBook1",rectcircle.id,None))
		val rectcircleBook2 = BookDao.save(Book("rectcircleBook2",rectcircle.id,None))
		
		//reader读者数据
		val reader1 = ReaderDao.save(Reader("R1","123456",15))
		val reader2 = ReaderDao.save(Reader("R2","123456",15))
		val reader3 = ReaderDao.save(Reader("R3","123456",15))
		
		
		val borrowal1 = BorrowalDao.save(Borrowal(tomBook1.id,reader1.id,new Date,None,0))
		val borrowal2 = BorrowalDao.save(Borrowal(tomBook2.id,reader1.id,new Date,None,0))
		
	}
}